package com.sk.netty.client;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@ChannelHandler.Sharable
public class EchoClientHandlerIn extends SimpleChannelInboundHandler<ByteBuf>{

    Logger logger = LoggerFactory.getLogger(EchoClientHandlerIn.class);

    @Override public void channelActive(ChannelHandlerContext ctx) throws Exception {
        logger.info("client ：channel 已激活");
        //当被通知是活跃当时候，给服务端发送一条信息
        ctx.writeAndFlush(Unpooled.copiedBuffer("Netty rocks!", CharsetUtil.UTF_8));
    }

    @Override public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        logger.info("client ：channel 未激活");
        super.channelInactive(ctx);
    }

    @Override public void channelRegistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("client ：channel 已注册");
        super.channelRegistered(ctx);
    }

    @Override public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        logger.info("client ：channel 未注册");
        super.channelUnregistered(ctx);
    }

    @Override public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        System.out.println("收到服务端信息："+msg.toString(CharsetUtil.UTF_8));
    }

    @Override public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("服务端消息接受完成"+ctx.close());
        //System.out.println("服务端消息接受完成");
    }

    //    @Override public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
//        System.out.println("收到消息："+((ByteBuf)msg).toString(CharsetUtil.UTF_8));
//    }

    @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
